package com.wlb365.financing.modules.schedule.job;

import com.google.common.collect.Maps;
import com.wlb365.financing.common.constants.ApiConstants;
import com.wlb365.financing.common.constants.SysConstant;
import com.wlb365.financing.common.utils.SdkHelper;
import com.wlb365.financing.common.utils.SpringContext;
import com.wlb365.financing.common.utils.StringUtils;
import com.wlb365.financing.modules.esign.request.QueryFlowSignersReq;
import com.wlb365.financing.modules.esign.response.FlowSignerDto;
import com.wlb365.financing.modules.esign.response.QueryFlowSignersRes;
import com.wlb365.financing.modules.sys.entity.Dept;
import com.wlb365.financing.modules.sys.entity.User;
import com.wlb365.financing.modules.sys.service.IDeptService;
import com.wlb365.financing.modules.sys.service.IUserService;
import com.wlb365.financing.modules.trade.request.VoucherPageReq;
import com.wlb365.financing.modules.trade.request.voucher.VoucherUpdateReq;
import com.wlb365.financing.modules.trade.response.QueryPageVoucherDTO;
import com.wlb365.financing.modules.trade.response.VoucherQueryRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 凭证签章状态同步.
 *
 * @author zwh
 * @version 1.0
 */
@Slf4j
@Component("VoucherSignStatusSyncJob")
public class VoucherSignStatusSyncJob extends QuartzJobBean {
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IUserService userService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        ThreadContext.bind(SpringContext.getBean(DefaultWebSecurityManager.class));
        log.info("同步凭证签章状态据开始");
//        IDeptService deptService = SpringContext.getBean(IDeptService.class);
//        IUserService userService = SpringContext.getBean(IUserService.class);
        Map<String, Object> params = Maps.newHashMap();
        params.put("current", 1);
        params.put("size", 50);
        //待供应商签章、待核心企业签章
        params.put("status", "02,22");
        VoucherQueryRes res = SdkHelper.execute(new VoucherPageReq(), params);
        if (!ApiConstants.SUCCESS_CODE.equals(res.getCode())) {
            log.error("获取凭证列表异常，" + res.getMsg() + "," + res.getSubMsg());
            return;
        }
        for(QueryPageVoucherDTO dto : res.getItems()) {
            if (StringUtils.isEmpty(dto.getSignFlowId())){
                continue;
            }
            //获取签署人列表
            Map<String, Object> p = Maps.newHashMap();
            p.put("flowId", dto.getSignFlowId());
            QueryFlowSignersRes signers = SdkHelper.execute(new QueryFlowSignersReq(), p);
            for (FlowSignerDto signer : signers.getSigners()){
                if (ApiConstants.SIGN_STATUS_2 == signer.getSignStatus() || ApiConstants.SIGN_STATUS_4 == signer.getSignStatus()){
                    User user = userService.getUserByAccount(signer.getSignerAccountId());
                    if (user == null){
                        log.info("同步签章数据时，签章账号：" + signer.getSignerAccountId() + "，不存在");
                        continue;
                    }
                    Dept dept = deptService.getById(user.getDeptId());
                    if (dept == null) {
                        log.info("同步签章数据时，签章机构：" + user.getDeptId() + "，不存在");
                        continue;
                    }

                    if (SysConstant.DEPT_TYPE_0 == dept.getType() && "02".equals(dto.getStatus())){
                        log.info("供应商 "+dept.getName()+" 签署完成，签署状态：" + signer.getSignStatus());
                        updateStatus(dto.getId(), dto.getStatus(), String.valueOf(signer.getSignStatus()));
                    } else if (SysConstant.DEPT_TYPE_1 == dept.getType() && "22".equals(dto.getStatus())){
                        log.info("核心企业 "+dept.getName()+" 签署完成，签署状态：" + signer.getSignStatus());
                        updateStatus(dto.getId(), dto.getStatus(), String.valueOf(signer.getSignStatus()));
                    }
                }
            }
        }
        log.info("同步签章状态结束");
    }

    private void updateStatus(String voucherId, String status, String signStatus) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("voucherId", voucherId);
        params.put("sign", signStatus);
        params.put("nextStatus", true);
        SdkHelper.execute(new VoucherUpdateReq(), params);
    }
}
